package net.xumf.support.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;

public class JWTUtil {

    /**
     * 生成签名,expireTime后过期
     *
     * @param username 用户名
     * @param time     过期时间s
     * @return 加密的token
     */
    public static Optional<String> sign(String username, String salt, long time) {
        try {
            Date date = new Date(System.currentTimeMillis() + time * 1000);
            Algorithm algorithm = Algorithm.HMAC256(salt);
            // 附带username信息
            String token = JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .withIssuedAt(new Date())
                    .sign(algorithm);
            return Optional.of(token);
        } catch (UnsupportedEncodingException e) {
            return Optional.empty();
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean
    isTokenExpired(String token) {
        Date now = Calendar.getInstance().getTime();
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getExpiresAt().before(now);
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的签发时间
     */
    public static Optional<Date> getIssuedAt(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return Optional.of(jwt.getIssuedAt());
        } catch (JWTDecodeException e) {
            return Optional.empty();
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static Optional<String> getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return Optional.of(jwt.getClaim("username").asString());
        } catch (JWTDecodeException e) {
            return Optional.empty();
        }
    }

    /**
     * 解密Token
     *
     * @param token token
     * @param salt 盐值
     * @return 是否验证成功
     */
    public static boolean verifyToken(String token, String salt) {
        Algorithm algorithm;
        try {
            algorithm = Algorithm.HMAC256(salt);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

}
